# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2022/9/1
# @Author  : moe@miku39.fun
# @File    : ParserURL.py
# @Software: PyCharm
import re


class URLOperation:
    def __init__(self, sess):
        self.sess = sess
        self.regexOfMd = re.compile(
            r"(https?://(w{3}[.]|m[.])?bilibili[.]com/bangumi/media/)?md(?P<mediaId>\d+)"
        )
        self.regexOfAv = re.compile(
            r"(https?://((b23[.]tv/)|(w{3}[.]|m[.])?bilibili[.]com/video/))?av(?P<avId>\d+)"
        )
        self.regexOfBv = re.compile(
            r"((b23[.]tv/)|https?://((w{3}[.]|m[.])?bilibili[.]com/video/))?(?P<bvId>(bv|BV)\w+)"
        )
        self.regexOfSs = re.compile(
            r"((b23[.]tv/)|https?://((w{3}[.]|m[.])?bilibili[.]com/bangumi/play/))?ss(?P<seasonId>\d+)"
        )
        self.regexOfEp = re.compile(
            r"(https?://((b23[.]tv/)|(w{3}[.]|m[.])?bilibili[.]com/bangumi/play/))?ep(?P<episodeId>\d+)"
        )

    def match(self, content):
        if avId := re.search(self.regexOfAv, content):
            video = avId.group("avId")
            return self.getFinalVideo(video, "aid")
        elif bvId := re.search(self.regexOfBv, content):
            video = bvId.group("bvId")
            return self.getFinalVideo(video, "bvid")
        elif mediaId := re.search(self.regexOfMd, content):
            video = mediaId.group("mediaId")
            return self.getFinalVideo(video)
        elif seasonId := re.search(self.regexOfSs, content):
            return {
                "idType": "season_id",
                "videoID": seasonId.group("seasonId"),
                "videoType": "animeFilm",
            }
        elif episodeId := re.search(self.regexOfEp, content):
            return {
                "idType": "ep_id",
                "videoID": episodeId.group("episodeId"),
                "videoType": "animeFilm",
            }
        else:
            return False

    def getFinalVideo(self, video_id, id_type=None):
        if id_type:
            url = "https://api.bilibili.com/x/web-interface/view"
            params = {id_type: video_id}
            response = self.sess.get(url=url, params=params).json()
            if response["code"] == 0:
                if redirectUrl := response["data"].get("redirect_url"):
                    if episodeId := re.search(self.regexOfEp, redirectUrl):
                        return {
                            "idType": "ep_id",
                            "videoID": episodeId.group("episodeId"),
                            "videoType": "animeFilm",
                        }
                else:
                    return {"idType": id_type, "videoID": video_id, "videoType": "video"}
            else:
                return False
        else:
            url = "https://api.bilibili.com/pgc/review/user"
            params = {"media_id": video_id}
            response = self.sess.get(url=url, params=params).json()
            if response["code"] == 0:
                return {
                    "idType": "season_id",
                    "videoID": response["result"]["media"]["season_id"],
                    "videoType": "animeFilm",
                }
            else:
                return False
